package com.lkl.utils;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class AlipayUtils {
    @Value("${zfb.SERVER_URL}")
    String SERVER_URL ;
    @Value("${zfb.APP_ID}")
    String APP_ID ;
    @Value("${zfb.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY ;
    @Value("${zfb.FORMAT}")
    String FORMAT ;
    @Value("${zfb.CHARSET}")
    String CHARSET ;
    @Value("${zfb.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY ;
    @Value("${zfb.SIGN_TYPE}")
    String SIGN_TYPE ;
    @Value("${zfb.RETURN_URL}")
    String RETURN_URL ;
    @Value("${zfb.NOTIFY_URL}")
    String NOTIFY_URL ;

    public static Logger logger = LoggerFactory.getLogger(AlipayUtils.class) ;

    public   String   pay (String orderid,Double money){
        AlipayClient alipayClient =  new DefaultAlipayClient(
                SERVER_URL ,
                APP_ID ,
                APP_PRIVATE_KEY,
                FORMAT ,
                CHARSET ,
                ALIPAY_PUBLIC_KEY ,
                SIGN_TYPE
        ) ;
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL); //在公共参数中设置回跳和通知地址
        Map map = new HashMap<>() ;
        map.put("out_trade_no" , orderid) ;
        map.put("total_amount" , money) ;
        map.put("subject" , "千锋商品购买kec") ;
        alipayRequest.setBizContent(JSON.toJSONString(map)); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        return form ;
    }

    public Map notifyResult(HttpServletRequest request){
        Map<String, String> requestParamsToMap = convertRequestParamsToMap(request);
        //验签操作
        Map returnMap = new HashMap();
        boolean signVerified=false;

        try {
            //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(requestParamsToMap,ALIPAY_PUBLIC_KEY , CHARSET , SIGN_TYPE) ;
            logger.error("验签是否成功：{}"+signVerified);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.error("验签异常：{}"+e.getErrMsg());
        }
        returnMap.put("signVerified",signVerified);
        returnMap.put("payResult",requestParamsToMap);
        return returnMap;
    }

    //退款
    public Integer refund(String orderDetailId , Double price){
        AlipayClient alipayClient = new DefaultAlipayClient(
                SERVER_URL ,
                APP_ID ,
                APP_PRIVATE_KEY ,
                FORMAT,
                CHARSET ,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderDetailId + "\"," +                    //订单号
                //"\"trade_no\":\"2014112611001004680003956707\"," +     //支付宝交易号
                "\"refund_amount\":\"" + price + "\"," +         //需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
                "\"refund_reason\":\"正常退款\"," +                       //退款的原因说明****
                "\"out_request_no\":\"HZ01RF001\"" +//标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传。
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println(response.getBody());
            //业务逻辑处理
            System.out.println("调用成功");
            return 1 ;
        } else {
            System.out.println("调用失败");
            logger.info("*****************退款申请失败！*********************");
            return 0 ;
        }
    }


    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

}
